package com.sgq.config.security.service;

import com.sgq.entity.Permission;
import com.sgq.entity.User;
import com.sgq.service.PermissionService;
import com.sgq.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author: 83778
 * @date: 2024-09-18 9:27
 * @desc:
 */
@Component
public class CustomerUserDetailsService implements UserDetailsService {
    @Autowired
    private UserService userService;

    @Autowired
    private PermissionService permissionService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        User user = userService.findUserByUserName(username);
        System.out.println("username = " + username);
        System.out.println("user = " + user);
        System.out.println("========================>"+username);
        if (user == null){
            throw new UsernameNotFoundException("用户名或密码错误");
        }

        List<Permission> permissions = permissionService.findPermissionListByUserId(user.getId());

        List<String> codes = permissions.stream()
                .filter(Objects::nonNull)
                .map(Permission::getCode)
                .filter(Objects::nonNull)
                .collect(Collectors.toList());
        String[] array = codes.toArray(new String[codes.size()]);
        System.out.println(username+" 具备的权限有 : " + Arrays.toString(array));
        //设置权限列表
        List<GrantedAuthority> authorities = AuthorityUtils.createAuthorityList(array);
        user.setAuthorities(authorities);
        user.setPermissions(permissions);
        return user;
    }
}
